// pages/formKeycard/formKeycard.js
import api from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    applyName: '',
    workno: '',
    branch: "",
    phone: "",
    visitorTypeHide: true,
    visitorType: "请选择",
    pertype: "",
    startdate: "",
    enddate: "",
    minDate: "",
    maxDate: "",
    company: "",
    visitorTypeList: [
      "正式员工",
      "实习人员",
      "长期驻场人员",
      "驻场支持人员",
      "总分行人员",
      "其他",
    ],
    currDate: '', // 当前日期
    visitorsList: [],
    showBtnArea: false,
    nextApprover: "",
    showDialog: false,
    requestId: -1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      // currDate: this.getCurrDate(),
      startdate: this.getCurrDate(),
      enddate: this.getCurrDate(),
     
    })
    this.getUserInfo()
    this.setDateRange(new Date(),14)

    if (options.id != null) {
      this.setData({
        requestId: options.id,
      })
      this.getRequestDetail()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //点击放大图片
  previewPic: function (e) {
      let imgUrls = [e.currentTarget.dataset.url]
      wx.previewImage({
        urls: imgUrls, //需要预览的图片http链接列表，注意是数组
        current: '', // 当前显示图片的http链接，默认是第一个
        success: function (res) {},
        fail: function (res) {},
        complete: function (res) {},
      })
    },

  // 显示遮罩层
  showModal: function (e) {
    let popup = e.currentTarget.dataset.index
    var that = this;

    that.setData({
      visitorTypeHide: popup == "visitor" ? false : true,
    })
    var animation = wx.createAnimation({
      duration: 600, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn(); //调用显示动画
    }, 200)
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500, //动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown(); //调用隐藏动画   
    setTimeout(function () {
      that.setData({
        visitorTypeHide: true,
      })
    }, 500) //先执行下滑动画，再隐藏模块
  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(700).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },

  // 人员类型变换
  visitorTypeChange: function (e) {
    let visitorType = e.detail.value
    let pertype = this.getPeopleType(false, visitorType)

    this.setData({
      visitorsList: [],
      employeesList: [],
      visitorType: visitorType,
      pertype: pertype,
      showBtnArea: false
    })
    this.hideModal()
  },

  // 人员类别文字与值转换
  getPeopleType: function (getText, value) {
    let tempList = ["", "", "", "", "正式员工", "实习人员", "长期驻场人员", "驻场支持人员", "总分行人员", "其他"]
    if (getText) {
      return tempList[value]
    } else {
      for (let i in tempList) {
        if (tempList[i] == value) {
          return i
        }
      }
    }
  },

  datePickerChange: function (e) {
    let type = e.currentTarget.dataset.type

    if (type == "start") {
      const selectedStartDay = e.detail.value;
      this.setData({
        startdate: selectedStartDay
      })
      this.setDateRange(selectedStartDay,14)
    } else {
      this.setData({
        enddate: e.detail.value
      })
    }
  },

  addVisitor: function () {
    if (this.data.visitorType == "请选择") {
      wx.showToast({
        title: '请选择人员类别',
        icon: "error"
      })
      return
    }

    let tempList = this.data.visitorsList
    let visitor = {
      visitName: "",
      department: "",
      startdate: this.getCurrDate(),
      enddate: this.getCurrDate(),
      jobDescription: "",
    }

    tempList.push(visitor)
    this.setData({
      visitorsList: tempList,
      showBtnArea: true
    })
  },

  // 获取当前日期
  getCurrDate: function () {
    let date = new Date()
    let currDate = date.getFullYear() + "-" + this.dateFormat(date.getMonth() + 1) + "-" + this.dateFormat(date.getDate())
    return currDate
  },


  setDateRange:function(selectedDay,days){
    if(selectedDay) {
      const startDateObj=new Date(selectedDay);
      const minDate = this.formatDate(startDateObj);
      const maxDate = this.formatDate(this.addDays(startDateObj,days));
      console.log(minDate+":"+maxDate)
      this.setData({
        minDate: minDate,
        maxDate: maxDate,
      });
    }
    else
    {
      this.setData({
              minDate:'',
              maxDate:'',
            });
    }
    
},

// 辅助函数：格式化日期为 YYYY-MM-DD
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 辅助函数：增加天数
  addDays(date, days) {
    const result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
  },

  // 日期格式调整
  dateFormat: function (time) {
    return time < 10 ? "0" + time : time
  },

  deleteVisitor: function (e) {
    // let type = e.currentTarget.dataset.type
    let index = e.currentTarget.dataset.index

    let tempList = this.data.visitorsList
    tempList.splice(index, 1)
    this.setData({
      visitorsList: tempList,
    })
  },

  inputChange: function (e) {
    let type = e.currentTarget.dataset.type

    if (type == "company") {
      this.setData({
        company: e.detail.value
      })
    } else {
      let tempList = this.data.visitorsList
      let index = e.currentTarget.dataset.index

      tempList[index].visitName = e.detail.value
      this.setData({
        visitorsList: tempList
      })
    }
  },

  uploadImage: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index
    let tempList = this.data.visitorsList

    wx.chooseImage({
      //限定上传张数x
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        //显示等待框
        wx.showLoading({
          title: '图片上传中',
          mask: true
        })
        //调取图片上传
        wx.uploadFile({
          //对象转字符串.join("")
          filePath: res.tempFilePaths.join(""),
          name: 'img',
          url: api.uploadImg,
          success: function (res) {
            wx.hideLoading()
            if (res.data.toString().includes("Too Large")) {
              wx.showToast({
                title: '图片超过1M',
                icon: 'error'
              })
            } else {
              var data = JSON.parse(res.data)
              if (data.data != null) {
                tempList[index].jobDescription = data.data.imgUrl
                that.setData({
                  visitorsList: tempList
                })
              }
              if (data.state == "1") {
                wx.showToast({
                  title: '图片上传成功',
                })
              } else if (data.state == "2") {
                wx.showToast({
                  title: '图片上传失败，请重新上传或选择分辨率较小的图片',
                  icon: 'error'
                })
              }
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '图片上传失败，请重新上传或选择分辨率较小的图片',
              icon: 'error'
            })
          },
          complete: () => {
            // console.log("complete")
          }
        })
      },
    })
  },

  validate: function () {
    if(this.data.startdate=='')
    {
      return "来访开始日期不能为空"
    }

    if(this.data.enddate=='')
    {
      return "来访结束日期不能为空"
    }

    if(this.data.enddate<this.data.startdate)
    {
      return "来访结束日期不能早于开始日期"
    }

    if(this.data.enddate>this.data.maxDate)
    {
      return "来访结束日期不能超过开始日期两周"
    }


    if (this.data.visitorsList.length <= 0) {
      return "请添加来访人员信息"
    } else if (this.data.pertype > 5 && this.data.department == "") {
      return "所属单位不能为空"
    } else if ((new Date(this.data.enddate.replace(/-/g, '/')).getTime() - new Date(this.data.startdate.replace(/-/g, '/')).getTime()) > 13 * 24 * 60 * 60 * 1000) {
      // 2022-8-18, 2022/8/18, 2022/08/18  都是00:00:00; 2022-08-18 是08:00:00
      return "申请时间超过14天，请线下提单"
    } else {
      let visitorsList = this.data.visitorsList
      for (let i = 0; i < visitorsList.length; i++) {
        if (visitorsList[i].visitName == "") {
          return "办卡人员姓名不能为空"
        }


        if (this.data.pertype > 7 && visitorsList[i].jobDescription == "") {
          return "请上传工作说明"
        }
        return "finished"
      }
    }
  },

  sendRequest: function (e) {
    // 0-保存 1-提交
    let url = e == 1 ? api.formSubmitRequest : api.formSaveRequest
    let _this = this

    //显示等待框
    wx.showLoading({
      title: '请稍候',
      mask: true
    })
    wx.request({
      url: url,
      method: "POST",
      data: {
        id: _this.data.requestId,
        applyName: _this.data.applyName,
        workno: _this.data.workno,
        branch: wx.getStorageSync("logindata").data.department,
        phone: _this.data.phone,
        applyType: 1,
        pertype: _this.data.pertype,
        startdate: _this.data.startdate,
        enddate: _this.data.enddate,
        company: _this.data.company,
        visitorDetailList: _this.data.visitorsList,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading()
        if (res.data.state == 1) {
          let message = e == 1 ? "提交成功" : "保存成功"
          wx.showToast({
            icon: 'success',
            title: message,
          })
          _this.goBack()
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },

  goBack: function () {
    if (wx.getStorageSync('source')) {
      // console.log('公众号退回')
      wx.reLaunch({
        url: '/pages/formHome/formHome'
      })
      wx.removeStorageSync('source')
    } else {
      // console.log('正常流程退回')
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  getNextApprover: function () {
    let isFinished = this.validate()
    if (isFinished != "finished") {
      // wx.showToast({
      //   icon: 'error',
      //   title: isFinished,
      // })
      wx.showModal({
        content: isFinished,
        showCancel: false
      })
      return
    }
    let _this = this

    wx.request({
      url: api.formGetNextApprover,
      method: "GET",
      data: {
        workno: _this.data.workno,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            showDialog: true,
            nextApprover: res.data.data.name
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.message,
          })
        }
      }
    })
  },

  cancel: function (e) {
    let btnIndex = e.detail.index

    if (btnIndex == 0) {
      this.setData({
        showDialog: false
      })
    } else {
      this.sendRequest(1)
    }
  },

  getUserInfo: function () {
    let _this = this
    wx.request({
      url: api.getUserInfo + '?workno=' + wx.getStorageSync("workNo"),
      method: "GET",
      success(res) {
        if (res.data.state == 1) {
          _this.setData({
            applyName: res.data.data[0].name,
            workno: res.data.data[0].workno,
            branch: res.data.data[0].depName,
            phone: res.data.data[0].mobile,
          })
        }
      }
    })
  },

  getRequestDetail: function (e) {
    let that = this

    wx.request({
      url: api.formRequestDetail + this.data.requestId,
      method: "GET",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success(res) {
        if (res.data.state == 1) {
          that.setData({
            visitorType: that.getPeopleType(true, res.data.data.pertype),
            pertype: res.data.data.pertype,
            visitorsList: res.data.data.visitorDetailList,
            company: res.data.data.company,
            startdate: res.data.data.startdate,
            enddate: res.data.data.enddate,
            showBtnArea: true
          })
        }
      }
    })
  },
})